package com.sk.update;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the  Activity that displays the current chat session.
 */
public class MainActivity extends Activity implements Runnable{
    // Debugging
    private static final String TAG = "MainActivity";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views
    // private TextView mTitle;
    //  private ListView mConversationView;
    // private EditText mOutEditText;
    private Button button_isp;

    private Button button_connect;

    private Button button_test;
    private TextView tv_filesize;

    FlikerProgressBar flikerProgressBar;

    Thread downLoadThread;

    //LinearLayout lv_show;
    //private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    //private ArrayAdapter<String> mNewDevicesArrayAdapter;

    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";


    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    //   private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;



    public int MCT_ISP_STATE = 0;
    public int MCT_ISP_LEN = 0;
    public byte[] checkcode = {0x00, 0x00, 0x00, 0x00};
    private TextView tv_state;
    private TextView tv_model;
    private TextView tv_number;
    private String mynamestr;
    private String mynamestr2;
    private String open_filename;
    public int FILE_CHECK_OK = 0;


    private float progress;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            flikerProgressBar.setProgress(msg.arg1);

            if(msg.arg1 == 100){
                flikerProgressBar.finishLoad();

            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (D) Log.e(TAG, "+++ ON CREATE +++");

        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(0xff63d7a6);
        } else {
            this.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        // Set up the window layout
        setContentView(R.layout.activity_main);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (D) Log.e(TAG, "++ ON START ++");


        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }


    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if (D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
            }
        }
    }

    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        //  mConversationView = (ListView) findViewById(R.id.in);
        //  mConversationView.setAdapter(mConversationArrayAdapter);

        tv_state = (TextView) findViewById(R.id.tv_state);
        tv_state.setText(getResources().getString(R.string.unconnected));
        tv_model = (TextView) findViewById(R.id.tv_model);
        tv_number = (TextView) findViewById(R.id.tv_number);


        button_connect = (Button) findViewById(R.id.button_connect);

        if (BluetoothChatService.sk_isp_connect==1){
            button_connect.setText(getString(R.string.connectsh));
        }
        button_connect.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //doDiscovery();
                //v.setVisibility(View.GONE);
                button_isp.setEnabled(true);
                progress=0;
                Message message = handler.obtainMessage();
                message.arg1 = (int) progress;
                handler.sendMessage(message);
                flikerProgressBar.reset();
                Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            }
        });


        //mAnimButtonLayout = (AnimButtonLayout) findViewById(R.id.anim_btn3);
        flikerProgressBar = (FlikerProgressBar) findViewById(R.id.flikerbar);


        // Initialize the compose field with a listener for the return key
        // mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        // mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        button_isp = (Button) findViewById(R.id.button_isp);
        button_isp.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                //TextView view = (TextView) findViewById(R.id.edit_text_out);
                //String message = view.getText().toString();

                //sendMessage(message);
                if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED){
                    button_isp.setEnabled(false);
                }
                MCT_ISP_STATE = 1;
                mConversationArrayAdapter.add("Erase Flash......  ");
                isp_handshank((byte) 1);
                //sendFile();

            }
        });

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        //  mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if (D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if (D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if (D) Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() {
        if (D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
                BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    public String bytesToHexName(byte[] src, int len) {

        StringBuilder stringBuilder = new StringBuilder("MCT_");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            // char c=(char)v;
            if (v == 0) {
                stringBuilder.append("00");
            } else {
                if (v > 15) {
                    String hv = Integer.toHexString(v).toUpperCase();//+" ";
                    stringBuilder.append(hv);
                } else {
                    String hv = "0" + Integer.toHexString(v).toUpperCase();
                    stringBuilder.append(hv);
                }
            }
        }
        stringBuilder.append(".ISP");
        return stringBuilder.toString();
    }


    public String bytesToHexString(byte[] src, int len) {

        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            // char c=(char)v;
            if (v == 0) {
                stringBuilder.append("00 ");
            } else {
                String hv = Integer.toHexString(v).toUpperCase() + " ";

                stringBuilder.append(hv);
            }
        }
        return stringBuilder.toString();
    }


    public String bytesToPerString(byte[] src, int len) {

        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            // char c=(char)v;
            if (v == 0) {
                stringBuilder.append("00 ");
            } else {
                String hv = Integer.toHexString(v).toUpperCase() + " ";

                stringBuilder.append(hv);
            }
        }
        return stringBuilder.toString();
    }

    private void isp_handshank(byte myx) {

        //	String info = "";
        //InputStream is =null;
        //	BufferedReader BufferedReader = null;
        byte[] b = new byte[32];

        b[0] = (byte) 0x4D;//M
        b[1] = (byte) 0x43;//C
        b[2] = (byte) 0x54;//T
        b[3] = (byte) myx;//CMD
        b[4] = (byte) 10;//LEN
        b[5] = (byte) 0x00;//MODEL1
        b[6] = (byte) 0x03;//MODEL2
        b[7] = (byte) 0x09;//MODEL3
        b[8] = (byte) 0x00;//MODEL4
        b[9] = (byte) 0x00;//CUSTUM
        MCT_ISP_STATE = 1;

        mChatService.write(b, 0, 10);

    }

 private void checkIspFile(){

 //	String info = "";

 	InputStream is =null;

 	//String hv;
 	  //Log.i(TAG, "fx-spp-write 039S File*** ");
     //mConversationArrayAdapter.add("Update ISP File......  ");
 	try {

 		String open_filename =bytesToHexName(checkcode,4);
 		//disp old file name.
 		  Log.i(TAG, "read-file-data-fx: " + open_filename);

 		is= getAssets().open(open_filename);
 		if (is != null)
        {
        	FILE_CHECK_OK=1;
        }else{
        	FILE_CHECK_OK=0;
        }


 	}catch (IOException e) {
 		e.printStackTrace();
		}finally{

			if (is != null)
         {
             try
             {
             	is.close();
             }
             catch (IOException e)
             {
                 e.printStackTrace();
             }
         }
		}

 }
    /*private void sendFile() {
        String hv;
        long filesize = 0;
        InputStream is = null;
        // BufferedReader BufferedReader = null;
        Log.i(TAG, "fx-spp-write 039S File*** ");
        try {

            open_filename = bytesToHexName(checkcode, 4);
            Log.i(TAG, "read-file-data-fx: " + open_filename);
            //tv_number.setText(open_filename);

            is = getAssets().open(open_filename);
            filesize = is.available();

            int i = 0;
            int len = 0;
            int total = 0x44000;
            byte[] b = new byte[256];
            //is.read(b);
            //dumy info
            int percent;
            int per1 = 0;
            long size = 0;
            int tmp = 0;


            while ((len = is.read(b)) != -1) {

                mChatService.write(b, 0, len);
                total += 256;

                percent = total * 100 / 0x80000;
                hv = Integer.toString(percent);
                //	  Log.i(TAG, "write isp data: " + hv);
                // mConversationArrayAdapter.add("Write [ "+hv+" %]");

                size+= len;

                if (((size*100/filesize)-tmp)==1) {
                    Log.i(TAG, "tmp: " + tmp);
                   // showTheButton(1);
                    ++tmp;
                }
                Log.i(TAG, "size: " + size);
                //tv_filesize.setText(size+"/"+filesize);
               // per1 = percent;
                tv_filesize.setText(size+"/"+filesize);

                if (total >= 0x80000) {
                    break;
                }

            }
            for (i = 0; i < 256; i++) b[i] = 0x00;
            while (total < 0x80000) {
                mChatService.write(b, 0, 256);
                total += 256;
                percent = total * 100 / 0x80000;

                hv = Integer.toString(percent);
                // mConversationArrayAdapter.add("Write [ "+hv+" %]");
                // showTheButton(percent);


            }

            //isp_handshank((byte)2);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }*/


    /**
     * Sends a message.
     *
     * @param message  A string of text to send.
     */
   /* private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }*/

    // The action listener for the EditText widget, to listen for the return key

    private TextView.OnEditorActionListener mWriteListener =
            new TextView.OnEditorActionListener() {
                public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
                    // If the action is a key-up event on the return key, send the message
                    if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                        String message = view.getText().toString();
                        //sendMessage(message);
                    }
                    if (D) Log.i(TAG, "END onEditorAction");
                    return true;
                }
            };


    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            // mTitle.setText(R.string.title_connected_to);
                            // mTitle.append(mConnectedDeviceName);
                            mConversationArrayAdapter.clear();
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            //mTitle.setText(R.string.title_connecting);
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            //mTitle.setText(R.string.title_not_connected);
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                    mConversationArrayAdapter.add("Me:  " + writeMessage);
                    Log.i(TAG, "fx-spp-write*** " + writeMessage);
                    break;

                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    String t = bytesToHexString(readBuf, 23);

                    // construct a string from the valid bytes in the buffer
                    // String readMessage = new String(readBuf, 0, msg.arg1);
                    // mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                    Log.i(TAG, "fx-spp-read: " + t);

            	   if((readBuf[0]==0x4D)&&(readBuf[1]==0x43)&&(readBuf[2]==0x54))//MCT
            	   {

            		   if(readBuf[3]==(byte)0xA1)
           	           {
           	    	   //4,5,6,7==ID NUMBER.
           	           if(readBuf[8]==0x01)
           	        	{
           	        	   checkcode[0]=readBuf[4];
           	        	   checkcode[1]=readBuf[5];
           	        	   checkcode[2]=readBuf[6];
           	        	   checkcode[3]=readBuf[7];
           	        	   FILE_CHECK_OK=0;

           	        	  Log.i(TAG, "fx-isp_check file ");

           	        	    checkIspFile();

                            byte[]myname = new byte[32];
                            int i;
                            for(i=0;i<32;i++)
                                myname[i]=readBuf[i+10];
                            mynamestr = new String(myname);

                                //mynamestr2 = new String(checkcode);


                           // Log.i(TAG, "ssssssssssssssssssss " + mynamestr2);
                            tv_model.setText(mynamestr);

                            String filename = bytesToHexName(checkcode, 4);
                            tv_number.setText(filename);

                            if(FILE_CHECK_OK==1)
           	        	    {
           	        	     Log.i(TAG, "OK,====Erase flash cmd==== ");

           	        	    	isp_handshank((byte)2); //erase.
                                button_isp.setText("开始升级");
           	        	    }else{
           	        	     Log.i(TAG, "*****ERROR,SEND 5 CMD**** ");
           	        	    	isp_handshank((byte)5);//error , no exist
           	        	    }
           	           // byte[]mydevice = new byte[32];
           	        		   //Log.i(TAG, "fx-isp_check2 ok: ");
           	        		  // sendFile();
           	        		  // Log.i(TAG, "write cmd2 ");
           	        		  // isp_handshank((byte)2);
           	        		  // isp_handshank((byte)2);
           	        		//   mConversationArrayAdapter.add("Write Isp Success!  ");
           	        	}

           	        }else  if(readBuf[3]==(byte)0xA2)
            	        {
            	    	   //4,5,6,7==ID NUMBER.
            	           if(readBuf[8]==0x01)
            	        	{
            	        	 //  checkcode[0]=readBuf[4];
            	        	  // checkcode[1]=readBuf[5];
            	        	  // checkcode[2]=readBuf[6];
            	        	  // checkcode[3]=readBuf[7];

            	        	   Log.i(TAG, "A2 CMD,===start send file=== ");
            	        		   //sendFile();
								   downLoad();
            	        		   //Log.i(TAG, "write cmd2 ");
            	        		  // isp_handshank((byte)2);
            	        		  // isp_handshank((byte)2);
            	        		   //mConversationArrayAdapter.add("Write Isp Success!  ");
            	        	}

            	        }else if(readBuf[3]==(byte)0xA3){//ok finish
            	        	FILE_CHECK_OK=0;
            	        	MCT_ISP_STATE=0;

                             Log.i(TAG, "send isp data finish ");
            	        } else if(readBuf[3]==(byte)0xA4){//erase percent
            	        	//FILE_CHECK_OK=0;
            	        //	MCT_ISP_STATE=0;
            	        	//  Log.i(TAG, "send isp data finish ");
            	        }
            	   }





                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    Toast.makeText(getApplicationContext(), "连接 "
                            + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    tv_state.setText(getResources().getString(R.string.connected));
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                            Toast.LENGTH_SHORT).show();
                    tv_state.setText(getResources().getString(R.string.unconnected));
                    break;
            }
        }
    };


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // Get the BLuetoothDevice object
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                    // Attempt to connect to the device
                    mChatService.connect(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occured
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }


/*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.scan:
                // Launch the DeviceListActivity to see devices and do scan
                Intent serverIntent = new Intent(this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                return true;
            case R.id.discoverable:
                // Ensure this device is discoverable by others
                ensureDiscoverable();
                return true;
        }
        return false;
    }
*/


    /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {
        if (D) Log.d(TAG, "doDiscovery()");

        // Indicate scanning in the title
        //  setProgressBarIndeterminateVisibility(true);
        //  setTitle(R.string.scanning);

        // Turn on sub-title for new devices
        //  findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

        // If we're already discovering, stop it
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBluetoothAdapter.startDiscovery();
    }

/*
    private void showTheButton(int number) {
        Log.e(TAG, "number=: " + number);
        mAnimButtonLayout.setTextSize(60f);
        mAnimButtonLayout.setState(AnimDownloadProgressButton.DOWNLOADING);
        mAnimButtonLayout.setProgressText("升级中", mAnimButtonLayout.getProgress() + number);
       // mAnimButtonLayout.setProgress(mAnimButtonLayout.getProgress());

        Log.d(TAG, "showTheButton: " + mAnimButtonLayout.getProgress());
        if (mAnimButtonLayout.getProgress() + 10 > 100) {
            //mAnimButtonLayout.setState(AnimDownloadProgressButton.INSTALLING);
            // mAnimButtonLayout.setCurrentText("安装中");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //mAnimButtonLayout.setState(AnimDownloadProgressButton.NORMAL);
                    mAnimButtonLayout.setCurrentText("打开");
                }
            }, 2000);   //2秒
        }
    }*/

    @Override
    public void run() {
        /*try {
            while( ! downLoadThread.isInterrupted()){
                float progress = flikerProgressBar.getProgress();
                progress  += 1;
                Thread.sleep(200);
                Message message = handler.obtainMessage();
                message.arg1 = (int) progress;
                handler.sendMessage(message);
                if(progress == 100){
                    break;
                }
            }*/

        long filesize = 0;
        InputStream is = null;
        // BufferedReader BufferedReader = null;
        Log.i(TAG, "fx-spp-write 039S File*** ");
        try {
            open_filename = bytesToHexName(checkcode, 4);
            Log.i(TAG, "read-file-data-fx: " + open_filename);

            is = getAssets().open(open_filename);
            filesize = is.available();

            int i = 0;
            int len = 0;
            int total = 0x44000;
            byte[] b = new byte[256];

            int percent;
       //     int per1 = 0;
            long size = 0;
            int tmp = 0;
            //progress = flikerProgressBar.getProgress();
            while ((len = is.read(b)) != -1) {

                mChatService.write(b, 0, len);
                total += 256;
                //percent = total * 100 / 0x80000;
                size+= len;
                    progress  = size*100/0x3C000;
                    //Log.i(TAG, "tmp0: " + progress);
                    Thread.sleep(20);
                    Message message = handler.obtainMessage();
                    message.arg1 = (int) progress;
                    handler.sendMessage(message);
                    //++tmp;
                    //Log.i(TAG, "size0: " + size);


                //tv_filesize.setText(size+"/"+filesize);
                // per1 = percent;
               // tv_filesize.setText(size+"/"+filesize);
                //Log.i(TAG, "total0== " + total);
                if (total >= 0x80000) {
                    break;
                }
                if(progress == 100){
                    break;
                }

            }



          //  Log.i(TAG, "total: " + total);
            while (true) {
                if (FILE_CHECK_OK == 0) {
                    Message message = handler.obtainMessage();
                    message.arg1 = 100;
                    handler.sendMessage(message);
                    button_isp.setText("升级完成");
                    break;
                }

                Thread.sleep(20);
            }
            //isp_handshank((byte)2);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void downLoad() {
        downLoadThread = new Thread(this);
        downLoadThread.start();
    }
}